import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import info from '@/views/info'
import layout from '@/views/layout'
import user from '@/views/layout/user'
import find from '@/views/layout/find'
import question from '@/views/layout/question'
import business from '@/views/layout/business'
import share from '@/views/layout/find/share'
import search from '@/views/layout/find/search'
import searchFace from '@/views/layout/find/searchFace'
import shareArticles from '@/views/layout/find/shareArticles'
import hotCity from '@/views/layout/find/hotCity'
import face from '@/views/layout/find/face'
import faceInfo from '@/views/layout/find/faceInfo'
import store from '@/store'
import edit from '@/views/info/edit'
import { Toast } from 'vant'
// 获取token
import { getLocal } from '@/utils/local'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: login
  },
  {
    path: '/share',
    name: 'share',
    component: share
  },
  {
    path: '/face',
    name: 'face',
    component: face
  },
  {
    path: '/faceInfo/:id',
    name: 'faceInfo',
    component: faceInfo
  },
  {
    path: '/search',
    name: 'search',
    component: search
  },
  {
    path: '/searchFace',
    name: 'searchFace',
    component: searchFace
  },
  {
    path: '/shareArticles/:id',
    name: 'shareArticles',
    component: shareArticles
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/info',
    name: 'info',
    component: info,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/hotCity',
    name: 'hotCity',
    component: hotCity
  },
  {
    path: '/layout',
    component: layout,
    children: [
      {
        path: '/user',
        name: 'user',
        component: user,
        meta: {
          needLogin: true
        }
      },
      {
        path: '/find',
        name: 'find',
        component: find
      },
      {
        path: '/question',
        name: 'question',
        component: question,
        meta: {
          needLogin: true
        }
      },
      {
        path: '/business',
        name: 'business',
        component: business
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
// 前置路由
router.beforeEach((to, from, next) => {
  // console.log('前置路由', to)
  // 判断是否需要token
  if (to.meta.needLogin) {
    // console.log('需要tk')
    // 判断是否有token
    if (getLocal()) {
      // console.log('有tk')
      if (store.state.userInfo) {
        // console.log('vuex有内容')
        next()
      } else {
        // console.log('获取vuex')
        store.dispatch('setUserInfo')
        next()
      }
    } else {
      Toast.fail('请先登录,谢谢')
      next('/login?redirect=' + to.fullPath)
    }
  } else {
    next()
  }
})
// 后置路由
// router.afterEach(to => {

// })

export default router
